<?php

// [ 批量采集更新开奖结果 ]
// POST pk10.exactCollect
// http://sg.51hub.cn/api?pk10.exactCollect&no=659649
// http://sg.io/api?pk10.exactCollect&no=659649
// 201 : 控制台输出提示消息,期号+1,继续采集
// 400 : 停止采集,控制台输出提示消息
// 422 : 期号不合法,停止采集,控制台输出提示消息
// 500 : 控制台输出提示消息,重新采集,连续3次后期号+1,继续采集

namespace app\api\resource\pk10;
use think\Db;
use think\facade\Validate;
use app\common\lib\ExactCollect as ExactCollectCommonLib;

class ExactCollect
{
    // 方法
    public $_method = ['GET','POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '批量采集更新开奖结果';
    // 参数
    public $_param  = [
        'no' => '期号',
    ];

    public function run(&$request)
    {
        $no = $request->param('no/d',0);

        if ( empty($no) ) return [422,'期号必须'];
        if ( !Validate::regex($no,'/^\d{6}$/') ) return [422,'期号格式不正确'];

        $res = ExactCollectCommonLib::run($no);
        if (!$res['ret']) return [ 400,$res['msg'] ];
        
        $res = $res['data'];
        $ret = Db::name('pk10')->where('no',$res['no'])->find();
        if ( is_null($ret) ) {
            // 新增
            $data['no']  = $res['no'];
            $data['v1']  = $res['item'][0];
            $data['v2']  = $res['item'][1];
            $data['v3']  = $res['item'][2];
            $data['v4']  = $res['item'][3];
            $data['v5']  = $res['item'][4];
            $data['v6']  = $res['item'][5];
            $data['v7']  = $res['item'][6];
            $data['v8']  = $res['item'][7];
            $data['v9']  = $res['item'][8];
            $data['v10'] = $res['item'][9];
            $data['create_time'] = $res['time'];
            $num = Db::name('pk10')->insert($data);
            return ($num > 0) ? [201,'新增成功'] : [500,'系统内部异常'];
        } else {
            // 更新
            $data['v1']  = $res['item'][0];
            $data['v2']  = $res['item'][1];
            $data['v3']  = $res['item'][2];
            $data['v4']  = $res['item'][3];
            $data['v5']  = $res['item'][4];
            $data['v6']  = $res['item'][5];
            $data['v7']  = $res['item'][6];
            $data['v8']  = $res['item'][7];
            $data['v9']  = $res['item'][8];
            $data['v10'] = $res['item'][9];
            $data['create_time'] = $res['time'];
            $num = Db::name('pk10')->where('no',$res['no'])->update($data);
            if ($num > 0) {
                return [201,'更新成功'];
            } elseif ($num == 0) {
                return [201,'无需更新'];
            } else {
                return [500,'系统内部异常'];
            }
        }
    }
}
